import argparse
import datetime as dt
import json
import logging
import pathlib
from logging.handlers import TimedRotatingFileHandler

import pymysql


class Config(object):
    """
    配置文件类。
    """
    set_flag = False

    @classmethod
    def set_config(cls):
        """
        根据配置文件设置全局配置项。
        """
        # 初始化一次
        if cls.set_flag == True:
            return

        cls.set_flag = True

        # 设置命令行参数，指定配置文件
        parser = argparse.ArgumentParser(description="全局配置.")
        parser.add_argument("-c", "--config", required=True, help="指定环境配置")
        parser.add_argument("-d", "--date", required=False, help="日期")

        # 解析命令行参数
        args = parser.parse_args()

        # 手动指定日期
        if args.date is None:
            cls.date = None
        else:
            cls.date = dt.datetime.strptime(args.date, "%Y%m%d")

        # 解析配置文件，展开到 Config 类
        with open(args.config) as f:
            for k, v in json.load(f).items():
                setattr(cls, k, v)

        # 初始化日志格式
        cls.set_logging()

        # 设置数据库连接参数
        cls.set_database()

    @classmethod
    def set_logging(cls):
        """
        设置日志。
        """
        filename = pathlib.Path(__file__) / "../.." / cls.logfile
        level = logging.INFO
        log_handler = TimedRotatingFileHandler(filename, when="D")
        log_handler.setLevel(level)
        formatter = logging.Formatter(
            "%(asctime)s,[%(filename)s:%(lineno)d],%(levelname)s,%(message)s",
            "%m-%d %H:%M:%S"
        )
        log_handler.setFormatter(formatter)
        logger = logging.getLogger("")
        logger.setLevel(level)
        logger.addHandler(log_handler)

    @classmethod
    def set_database(cls):
        """
        设置数据库连接参数。
        """
        cls.db_bi["charset"] = "utf8mb4"
        cls.db_bi["cursorclass"] = pymysql.cursors.DictCursor

        cls.ofs_delivery_center["charset"] = "utf8mb4"
        cls.ofs_delivery_center["cursorclass"] = pymysql.cursors.DictCursor

        cls.ofs_shop_center["charset"] = "utf8mb4"
        cls.ofs_shop_center["cursorclass"] = pymysql.cursors.DictCursor

        cls.ofs_work_center["charset"] = "utf8mb4"
        cls.ofs_work_center["cursorclass"] = pymysql.cursors.DictCursor